/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.Enum.PayStatusEnum;
import com.ykht.proj.activity.constant.CardConstant;
import com.ykht.proj.activity.dto.CnActivityOrderDTO;
import com.ykht.proj.activity.dto.CnActivityOrderExportReq;
import com.ykht.proj.activity.dto.EntExportRedeemCode;
import com.ykht.proj.activity.service.VInfoService;
import com.ykht.proj.activity.vo.VOrderCardVo;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.activity.entity.VOrderCard;
import com.ykht.proj.activity.service.VOrderCardService;
import com.ykht.proj.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


/**
 * 订单和卡的关联表
 *
 * @author csg
 * @date 2021-05-21 14:22:31
 */
@RestController
@AllArgsConstructor
@RequestMapping("/vordercard" )
@Api(value = "vordercard", tags = "订单和卡的关联表管理")
@Slf4j
public class VOrderCardController {

	public static final String 卡_ID = "卡ID";
	private final  VOrderCardService vOrderCardService;
	private final VInfoService vInfoService;
	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param vOrderCard 订单和卡的关联表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page" )
	@PreAuthorize("@pms.hasPermission('activity_vordercard_view')" )
	public R getVOrderCardPage(Page page, VOrderCard vOrderCard) {
		return R.ok(vOrderCardService.page(page, Wrappers.query(vOrderCard)));
	}

	/**
	 * 企业购买卡列表 分页查询
	 * @param page 分页对象
	 * @param vOrderCardVo 订单和卡的关联表
	 * @return
	 */
	@ApiOperation(value = "企业购买卡列表 分页查询", notes = "企业购买卡列表 分页查询")
	@GetMapping("/getEntOrderCardPage" )
	public R getEntOrderCardPage(Page page, VOrderCardVo vOrderCardVo) {
		log.info("->企业购买卡列表 分页查询{}{}", page, vOrderCardVo);
		vOrderCardVo.setEnterpriseId(SecurityUtils.getSjId());
		IPage<VOrderCardVo> iPage = vOrderCardService.getEntOrderCardPage(page, vOrderCardVo);
		return R.ok(iPage);
	}

	/**
	 * 企业购买卡详情列表 分页查询
	 * @param page 分页对象
	 * @param vOrderCardVo 订单和卡的关联表
	 * @return
	 */
	@ApiOperation(value = "企业购买卡详情列表 分页查询", notes = "企业购买卡详情列表 分页查询")
	@GetMapping("/getEntOrderCardDetailsPage" )
	public R getEntOrderCardDetailsPage(Page page, VOrderCardVo vOrderCardVo) {
		log.info("->企业购买卡详情列表 分页查询{}{}", page, vOrderCardVo);
//		vOrderCardVo.setEnterpriseId(SecurityUtils.getSjId());
		IPage<VOrderCardVo> iPage = vOrderCardService.getEntOrderCardDetailsPage(page, vOrderCardVo);
		return R.ok(iPage);
	}


	/**
     * 通过id查询订单和卡的关联表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('activity_vordercard_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(vOrderCardService.getById(id));
    }

    /**
     * 新增订单和卡的关联表
     * @param vOrderCard 订单和卡的关联表
     * @return R
     */
    @ApiOperation(value = "新增订单和卡的关联表", notes = "新增订单和卡的关联表")
    @SysLog("新增订单和卡的关联表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('activity_vordercard_add')" )
    public R save(@RequestBody VOrderCard vOrderCard) {
        return R.ok(vOrderCardService.save(vOrderCard));
    }

    /**
     * 修改订单和卡的关联表
     * @param vOrderCard 订单和卡的关联表
     * @return R
     */
    @ApiOperation(value = "修改订单和卡的关联表", notes = "修改订单和卡的关联表")
    @SysLog("修改订单和卡的关联表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('activity_vordercard_edit')" )
    public R updateById(@RequestBody VOrderCard vOrderCard) {
        return R.ok(vOrderCardService.updateById(vOrderCard));
    }

    /**
     * 通过id删除订单和卡的关联表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除订单和卡的关联表", notes = "通过id删除订单和卡的关联表")
    @SysLog("通过id删除订单和卡的关联表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('activity_vordercard_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(vOrderCardService.removeById(id));
    }


	/**
	 * 新增/修改 卡激活有效期
	 * @param vOrderCard 订单和卡的关联表
	 * @return R
	 */
	@ApiOperation(value = "新增/修改 卡激活有效期", notes = "新增/修改 卡激活有效期")
	@SysLog("新增/修改 卡激活有效期" )
	@PostMapping("/updateActivationTime")
	public R updateActivationTime(@RequestBody VOrderCard vOrderCard) {
		log.info("->新增/修改 卡激活有效期{}", vOrderCard);
		vOrderCardService.updateActivationTime(vOrderCard);
		return R.ok();
	}


	/**
	 * 企业 导出兑换码excel
	 * @param vOrderCardVo 订单和卡的关联表
	 * @return
	 */
	@ApiOperation(value = "企业 导出兑换码excel", notes = "企业 导出兑换码excel")
	@GetMapping("/getEntExportRedeemCode" )
	public void getEntExportRedeemCode(VOrderCardVo vOrderCardVo) {
		log.info("->企业 导出兑换码excel", vOrderCardVo);
		List<VOrderCardVo> dtoList = vOrderCardService.getEntExportRedeemCode(vOrderCardVo);
		List<EntExportRedeemCode> bean = new ArrayList<>();
		// 日期转换
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		dtoList.stream().forEach(itme -> {
			if (itme.getCardStatus().equals(CardConstant.CARD_STATUS_WDH)) {
				itme.setCardStatusShow("待开卡");
			} else  {
				itme.setCardStatusShow("已开卡");
			}
			if (null != itme.getStartTime()){
				itme.setStartTimeShow(dateTimeFormatter.format(itme.getStartTime()));
			}
			if (null != itme.getEndTime()){
				itme.setEndTimeShow(dateTimeFormatter.format(itme.getEndTime()));
			}
			bean.add(BeanUtil.toBean(itme, EntExportRedeemCode.class));
		});
		ExcelWriter writer = null;
		ServletOutputStream out = null;
		HttpServletResponse response = null;
		try {
			writer = ExcelUtil.getWriter(true);
			response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
			//自定义标题名
			writer.addHeaderAlias("id", "序号");
			writer.addHeaderAlias("cardId", "卡ID");
			writer.addHeaderAlias("cardName", "卡名称");
			writer.addHeaderAlias("vipAccount", "卡号");
			writer.addHeaderAlias("redeemCode", "兑换码");
			writer.addHeaderAlias("personName", "持卡人");
			writer.addHeaderAlias("personPhone", "手机号");
			writer.addHeaderAlias("cardStatusShow", "状态");
			writer.addHeaderAlias("startTimeShow", "开卡时间");
			writer.addHeaderAlias("endTimeShow", "截止时间");

			// 一次性写出内容，使用默认样式，强制输出标题
			writer.write(bean, true);
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			//这里容易乱码 处理
			String name = "卡核销码";
			name = URLEncoder.encode(name, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
			out = response.getOutputStream();
			writer.flush(out, true);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭writer
			writer.close();
		}
		//关闭输出Servlet流
		IoUtil.close(out);
	}

	/**
	 * 企业  绑定卡
	 * @param vOrderCardVo 订单和卡的关联表
	 * @return
	 */
	@ApiOperation(value = "企业  绑定卡", notes = "企业  绑定卡")
	@GetMapping("/entBingDingCard" )
	public R entBinDingCard(VOrderCardVo vOrderCardVo) {
		log.info("->企业  绑定卡", vOrderCardVo);
		return vInfoService.entBinDingCard(vOrderCardVo);
	}

}
